#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import strict_hdds
import strict_hwcfg
from fm_util import Util
from fm_param import FmConst
from helper_bbki import BbkiWrapper
from helper_dyncfg import DynCfgModifier
from helper_remote import RemoteOrLocalBuild


class FmSysCleaner:

    def __init__(self, param):
        self.param = param
        self.infoPrinter = self.param.infoPrinter

    def clean(self, bPretend):
        self.infoPrinter.printInfo(">> Preparing...")
        machine = None
        layout = None
        if True:
            self.param.sysChecker.init(False, False)
            self.param.sysChecker.basicCheck(repositoryOverlayCheck=True)

            DynCfgModifier.update()

            machine = strict_hwcfg.probe()

            if self.param.runMode in ["normal", "setup"]:
                layout = strict_hdds.get_storage_layout()
            else:
                layout = None

            print("")

        # clean old kernel files
        with strict_hdds.BootDirWriter(layout):
            with RemoteOrLocalBuild(self.infoPrinter) as obj:
                self.infoPrinter.printInfo(">> Removing old kernel files...")

                bFileRemoved = False
                with obj.getExecContext(syncDownType="kernel") as ctx:
                    resultFile = os.path.join(self.param.tmpDir, "result.txt")
                    ctx.exec(os.path.join(FmConst.libexecDir, "op-clean-kernel.py"),
                             Util.boolToStr01(bPretend),
                             resultFile)
                    bFileRemoved = self._parseKernelCleanResult(ctx.getFile(resultFile, "iso8859-1"))
                    print("")

                if bFileRemoved:
                    self.infoPrinter.printInfo(">> Updating boot-loader...")
                    if self.param.runMode in ["normal", "setup"]:
                        BbkiWrapper(machine, layout=layout).updateBootloader()
                    else:
                        print("WARNING: Running in \"%s\" mode, do NOT maniplate boot-loader!!!" % (self.param.runMode))
                    print("")

                if layout is not None and layout.name in ["efi-btrfs", "efi-bcache-btrfs", "efi-bcachefs"]:
                    dstList = layout.get_pending_esp_list()
                    if bFileRemoved and len(dstList) > 0:
                        with self.infoPrinter.printInfoAndIndent(">> Synchronizing boot partitions..."):
                            for dst in dstList:
                                self.infoPrinter.printInfo("        - %s to %s..." % (layout.get_esp(), dst))
                                layout.sync_esp(dst)
                        print("")

                with obj.getExecContext(syncDownType="system") as ctx:
                    # clean not-used packages and USE flags
                    self.infoPrinter.printInfo(">> Cleaning packages...")
                    ctx.exec(os.path.join(FmConst.libexecDir, "op-clean-packages-useflags.py"),
                             Util.boolToStr01(bPretend))
                    print("")

                    # clean distfiles
                    self.infoPrinter.printInfo(">> Cleaning %s..." % (FmConst.distDir))
                    ctx.exec("eclean-dist")
                    print("")

    def _parseKernelCleanResult(self, result):
        lines = result.split("\n")
        lines = [x.rstrip() for x in lines if x.rstrip() != ""]
        assert len(lines) == 1
        return (lines[0] != "0")
